package user;

import book.Book;
import book.Library;
import book.PairOfUidAndBookId;
import constant.Constant;
import utils.AnalyzingBorrowedBook;
import utils.LibrarySingleton;
import utils.ScannerSingleton;

import java.io.IOException;
import java.util.Scanner;

public class NormalUser extends User{

    //表示用户已经借阅图书相关信息（userID bookID）
    private PairOfUidAndBookId[] pairOfUidAndBookIds;
    //当前书籍的借阅量
    private int borrowedCount;
    //最多节约的图书数量
    private static final int BORROW_BOOK_MAX_NUM = 5;
    private final AnalyzingBorrowedBook analyzingBorrowedBook = new AnalyzingBorrowedBook();

    private Scanner scanner = null;
    public Library library = null;
    public NormalUser(String name , int userID) throws IOException {
        super(name,userID,"普通用户");
        loadBorrowedBook();
        scanner = ScannerSingleton.getInstance();
        library = LibrarySingleton.getInstance();

    }

    //文件的使用
    private void loadBorrowedBook() throws IOException {
        PairOfUidAndBookId[] allBorrowedBook;

        //1.先加载文件当中的借阅信息
        allBorrowedBook = analyzingBorrowedBook.loadObject(Constant.BORROWED_BOOK_FILE_NAME);
        //2.然后默认已经借阅的书籍的最大容量为BORROW_BOOK_MAX_NUM = 5
        pairOfUidAndBookIds = new PairOfUidAndBookId[Constant.BORROW_BOOK_MAX_NUM];
        //3.没有读到已经借阅的图书信息
        if(allBorrowedBook == null){
            borrowedCount = 0;
        }else{
            //4.读到已经借阅图书的信息,首先查看读到的数组的长度是多少
            int allBorrowedBookLen = allBorrowedBook.length;
            //5. 如果读取到了10本书被借阅 但是当前pairOfUidAndBookIds.length数组⻓度⼩于10
            if(allBorrowedBookLen > pairOfUidAndBookIds.length){
                //6. 按照实际情况进⾏分配数组内存
                pairOfUidAndBookIds = new PairOfUidAndBookId[allBorrowedBookLen];
            }
            //7.把数据拷贝回已经借阅图书信息的数组中
            for (int i = 0; i < allBorrowedBookLen; i++) {
                pairOfUidAndBookIds[i] = allBorrowedBook[i];
            }
            //8.更新当前实际借阅书籍的书籍数量
            borrowedCount = allBorrowedBookLen;
        }
    }
    private void storeBorrowedBook() {
        try {
            analyzingBorrowedBook.storeObject(pairOfUidAndBookIds,
                    Constant.BORROWED_BOOK_FILE_NAME);
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public int display() {
        System.out.println("普通⽤⼾ " + name + " 的操作菜单:");
        System.out.println("1. 查找图书");
        System.out.println("2. 打印所有的图书");
        System.out.println("3. 退出系统");
        System.out.println("4. 借阅图书");
        System.out.println("5. 归还图书");
        System.out.println("6. 查看当前个⼈借阅情况");
        System.out.println("请选择你的操作：");
        return scanner.nextInt();
    }

    //借阅图书
    public void borrowBook() throws IOException {
        scanner.nextLine();
        System.out.println("请输⼊你要借阅图书的id：");
        int bookId = scanner.nextInt();
        scanner.nextLine();

        //如果书架没有书 不能借阅
        if (library.bookCount == 0) {
            System.out.println("书架没有书籍暂且不能借阅");
            return;
        }
        //加载已借阅的图书信息
        loadBorrowedBook();

        //判断要借阅的书 是否存在
        Book book = library.searchById(bookId);
        if(book == null) {
            System.out.println("没有该id的相关书籍："+bookId);
            return;
        }
        for (int i = 0; i < borrowedCount; i++) {
            PairOfUidAndBookId pairOfUidAndBookId = pairOfUidAndBookIds[i];

            if(pairOfUidAndBookId.getBookID() == book.getBookId()) {
                if(pairOfUidAndBookId.getUserID() == getUserID()){
                    System.out.println("这本书你已经借阅过了，你的id是 ： " + getUserID());
                    return;
                }else {
                    System.out.println("这本书已经被别人借阅过了，他的id是 ： " + pairOfUidAndBookId.getUserID());
                    return;
                }
            }
        }
        library.borrowBook(bookId);

        //封装对象写到 借阅表当中
        PairOfUidAndBookId pairOfUidAndBookId = new PairOfUidAndBookId(userID, book.getBookId());
        pairOfUidAndBookIds[borrowedCount] = pairOfUidAndBookId;
        borrowedCount++;
        //存储借阅图书
        storeBorrowedBook();
        System.out.println("借阅成功！");



    }
    //归还图书
    public void returnBook() throws IOException {
        loadBorrowedBook();
        if (borrowedCount == 0) {
            System.out.println("目前没有用户借阅过书籍");
            return;
        }

        scanner.nextLine(); // 清除缓冲区残留的换行符
        System.out.println("请输入你要归还图书的ID：");
        int bookId = scanner.nextInt();
        scanner.nextLine(); // 清除缓冲区残留的换行符

        // 判断要归还的书是否存在
        Book book = library.searchById(bookId);
        if (book == null) {
            System.out.println("没有该ID的相关书籍：" + bookId);
            return;
        }

        // 检查用户是否借阅了这本书
        for (int i = 0; i < borrowedCount; i++) {
            // 如果书的ID匹配
            if (pairOfUidAndBookIds[i].getBookID() == book.getBookId()) {
                // 检查是否是当前用户借阅的
                if (getUserID() == pairOfUidAndBookIds[i].getUserID()) {
                    library.returnBook(bookId);
                    System.out.println("图书 '" + book.getTitle() + "' 已成功归还。");

                    // 用最后一本书替换归还的书
                    pairOfUidAndBookIds[i] = pairOfUidAndBookIds[borrowedCount - 1];
                    // 清空最后一个位置
                    pairOfUidAndBookIds[borrowedCount - 1] = null;
                    borrowedCount--;
                    storeBorrowedBook();
                } else {
                    System.out.println("该书籍不是你借阅的书籍，不能归还：" + book.getTitle());
                }
                return;
            }
        }

        // 如果循环结束仍未找到匹配的借阅记录
        System.out.println("你没有借阅该书籍，不需要归还，书籍ID为：" + bookId);

    }
    // 查看个⼈借阅情况
    public void viewBorrowBooks() throws IOException {
        //读取当前借阅所有⽤⼾的借阅书籍的情况
        loadBorrowedBook();
        System.out.println("您的借阅情况如下：");
        if (borrowedCount == 0) {
            System.out.println("⽬前没有借阅记录.....");
        } else {
            boolean flg = false;
            for (int i = 0; i < borrowedCount; i++) {
        //这⾥只能查看属于⾃⼰借阅的情况
        //⽤⼾ID相同的情况下，使⽤书籍ID查询书籍
                if(pairOfUidAndBookIds[i].getUserID() == userID) {
                    flg = true;
                    Book book = library.searchById(pairOfUidAndBookIds[i].getBookID());
                    System.out.println(book);
                }
            }
            if(!flg) {
                System.out.println("你没有借阅过书籍！");
            }
        }

    }
}


